import React, { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import {
  SearchOutlined,
  SyncOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleFilled,
  DoubleRightOutlined,
} from "@ant-design/icons";
import {
  Button,
  Form,
  Input,
  Select,
  Row,
  Col,
  DatePicker,
  Flex,
  Space,
  Modal,
  Dropdown,
  Switch,
} from "antd";
const { confirm } = Modal;
import type { MenuProps } from "antd";
import TreeWarpper from "@/components/tree";
import type { DataNode } from "antd/es/tree";
import TableWarpper from "@/components/TableWarpper";
import ModalDialog from "@/components/modalDialog";
import AddUser from "./components/addUser";
import { debounce } from "@/utils";
import { hasPermi } from "@/utils/permission.ts";

const { Option } = Select;
const { RangePicker } = DatePicker;

export const user = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [formPassWord] = Form.useForm();
  // 树数据
  const initTreeData: DataNode[] = [
    {
      title: "Expand to load",
      key: "0",
      children: [
        {
          title: "Expand to load",
          key: "4",
          children: [
            {
              title: "Expand to load1",
              key: "4-1",
              children: [{ title: "范伟东", key: "4-2" }],
            },
          ],
        },
        {
          title: "Expand to load",
          key: "1",
          children: [{ title: "范伟东", key: "1-1" }],
        },
        {
          title: "Expand to load",
          key: "3",
          children: [{ title: "xxxx", key: "3-1" }],
        },
        { title: "Tree Node", key: "2", isLeaf: true },
        { title: "mmmm", key: "5", isLeaf: true },
      ],
    },
  ];
  const formRef = useRef();
  const [modalSatus, setModalStatus] = useState(false);

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const [data, setData] = useState([]);
  const [defaultCurrent, setDefaultCurrent] = useState(1);
  const [total, setTotal] = useState();
  const [addIsModal, setAddIsModal] = useState({
    isModalStatus: false,
    isModalTitle: "",
  });

  const [userInfo, setUserInfo] = useState({});

  useEffect(() => {
    let data1 = [];
    for (let i = 0; i < 46; i++) {
      data1.push({
        key: i,
        name: `Edward King ${i}`,
        status: 0,
        address: `London, Park Lane no. ${i}`,
      });
    }
    setData(data1);
    setTotal(data1.length);
  }, []);

  //表格数据
  const columns = [
    // {
    //   title: "序号",
    //   dataIndex: "",
    //   key: "index",
    // //   render: (_, record, index) => {
    // //     return (
    // //         <span>{index + 1}</span>
    // //     )
    // //   },
    //       render: (_, record, index) => index + 1
    // },
    {
      title: "用户名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (_, record, index) => (
        <Switch
          checked={record.status}
          onChange={(e) => onSwitch(e, record, index)}
        />
      ),
    },
    {
      title: "地址",
      dataIndex: "address",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          {hasPermi("system:user:edit") && (
            <a onClick={(e) => rowEdit(record)}>
              <EditOutlined /> 修改
            </a>
          )}
          {hasPermi("system:user:del") && (
            <a onClick={(e) => rowDel(record)}>
              <DeleteOutlined /> 删除
            </a>
          )}
          {hasPermi("system:user:more") && (
            <Dropdown
              menu={{
                items,
                onClick: (key) => {
                  return handleDropdown(record, key);
                },
              }}
              placement="bottom"
            >
              <a>
                <DoubleRightOutlined /> 更多
              </a>
            </Dropdown>
          )}
        </Space>
      ),
    },
  ];
  const items: MenuProps["items"] = [
    {
      key: "1",
      label: <span className="dropdown-item">重置密码</span>,
    },
    {
      key: "2",
      label: <span className="dropdown-item">分配角色</span>,
    },
  ];

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    // console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  // 表格选择
  const rowSelection = {
    // type: 'checkbox', checkbox | radio
    selectedRowKeys,
    hideSelectAll: false,
    onChange: onSelectChange,
  };

  const onChangePage = (pageNum, pageSize) => {
    // console.log('e ======', pageNum, pageSize)
  };

  // 查询
  const onFinish = (values: any) => {
    console.log(values);
  };

  // 重置
  const onReset = () => {
    form.resetFields();
  };

  const handleUser = () => {
    setUserInfo({});
    setAddIsModal({
      isModalStatus: true,
      isModalTitle: "新增用户",
    });
  };

  const onModalCancel = (data) => {
    setAddIsModal(data);
  };

  const onModalFinish = (values) => {
    console.log(values);
    setAddIsModal({
      isModalStatus: false,
      isModalTitle: "",
    });
  };

  // 行编辑
  const rowEdit = (record) => {
    // console.log("修改: ", record);
    setUserInfo(record);
    setAddIsModal({
      isModalStatus: true,
      isModalTitle: "修改用户",
    });
  };
  // 行删除
  const rowDel = debounce(
    (record) => {
      // console.log("删除: ", record);
      confirm({
        title: "Are you sure delete this task?",
        icon: <ExclamationCircleFilled />,
        content: "Some descriptions",
        okText: "确认",
        cancelText: "再想想",
        onOk() {
          console.log("OK");
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    },
    500,
    true
  );

  // 重置密码
  const handleDropdown = (record, { key }) => {
    // console.log("1111", record);
    // console.log("1111", key);
    if (key == 2) {
      navigate("/user/role");
    } else {
      formPassWord.resetFields();
      setModalStatus(true);
    }
  };

  // 切换状态
  const onSwitch = debounce(
    (checked, row, index) => {
      // console.log("checked -----", checked, row, index);
      let data2 = JSON.parse(JSON.stringify(data));
      confirm({
        title: "系统提示",
        icon: <ExclamationCircleFilled />,
        content: `确认要${!checked ? "停用" : "启用"}${row.name}用户吗？`,
        okText: "确认",
        cancelText: "再想想",
        onOk() {
          console.log("OK");
          data2[index].status = !checked ? 0 : 1;
          // console.log(data2, "data2");
          setData(data2);
        },
        onCancel() {
          data2[index].status = !checked ? 1 : 0;
          // console.log(data2, "data2");
          setData(data2);
        },
      });
    },
    500,
    true
  );

  const handleDel = debounce(
    () => {
      // console.log("删除", selectedRowKeys);

      confirm({
        title: "Are you sure delete this task?",
        icon: <ExclamationCircleFilled />,
        content: "Some descriptions",
        okText: "确认",
        cancelText: "再想想",
        onOk() {
          console.log("OK");
          setSelectedRowKeys([]);
        },
        onCancel() {
          console.log("Cancel");
        },
      });
    },
    500,
    true
  );

  const onHandleSelect = (data, node) => {
    console.log("onHandleSelect", data, node);
  };

  const handleModalCancel = (data) => {
    // console.log(data)
    setModalStatus(data.isModalStatus);
  };

  const handleOk = (values) => {
    console.log(values);
    setModalStatus(false);
  };

  const contentSlot = (
    <div>
      <Form form={formPassWord} name="basic" onFinish={handleOk} ref={formRef}>
        <Form.Item name="passWord" label="密码">
          <Input placeholder="请输入 密码" />
        </Form.Item>
      </Form>
    </div>
  );

  // 表格配置
  const tableSetting = {
    rowSelection: rowSelection,
    columns: columns,
    data: data,
    bordered: false,
  };
  // 分页配置
  const paginationSetting = {
    showSizeChanger: true,
    showQuickJumper: true,
    defaultCurrent: defaultCurrent,
    total: total,
  };
  return (
    <div className="user pageWarpper">
      <Row>
        <Col span={4}>
          <TreeWarpper
            defaultExpandAll
            inputWarpper={true}
            initTreeData={initTreeData}
            width={"100%"}
            onHandleSelect={onHandleSelect}
          />
        </Col>
        <Col span={20} style={{ paddingLeft: "10px" }}>
          <Form form={form} name="control-hooks" onFinish={onFinish}>
            <Row gutter={20}>
              <Col span={6}>
                <Form.Item name="username" label="用户名">
                  <Input placeholder="请输入 用户名" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="phone" label="手机号">
                  <Input placeholder="请输入 手机号" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="status" label="状态">
                  <Select placeholder="请选择 状态" allowClear>
                    <Option value="正常">正常</Option>
                    <Option value="停用">停用</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="createTime" label="创建日期">
                  <RangePicker />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    <SearchOutlined />
                    查询
                  </Button>
                  <Button
                    htmlType="button"
                    onClick={onReset}
                    style={{ marginLeft: 10 }}
                  >
                    <SyncOutlined />
                    重置
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
          <Flex gap="small" wrap="wrap" style={{ marginBottom: "12px" }}>
            {hasPermi("system:user:add") && (
              <Button type="primary" onClick={(e) => handleUser()}>
                新增
              </Button>
            )}

            <Button
              danger
              disabled={selectedRowKeys.length ? false : true}
              onClick={(e) => handleDel()}
            >
              删除
            </Button>
            <Button type="primary">导入</Button>
            <Button type="primary">导出</Button>
          </Flex>
          <TableWarpper
            onChangePage={onChangePage}
            tableSetting={tableSetting}
            paginationSetting={paginationSetting}
          />
        </Col>
      </Row>
      {modalSatus && (
        <ModalDialog
          formRef={formRef}
          isModal={{ isModalTitle: "重置密码", isModalStatus: modalSatus }}
          handleModalCancel={handleModalCancel}
          contentSlot={contentSlot}
        />
      )}

      {addIsModal.isModalStatus && (
        <AddUser
          isModal={addIsModal}
          userInfo={userInfo}
          onModalCancel={onModalCancel}
          onModalFinish={onModalFinish}
        />
      )}
    </div>
  );
};

export default user;
